package com.pps.fragment;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pps.activity.R;
import com.pps.adapter.MyDetailGridAdapter;
import com.pps.async.ImageLoader;
import com.pps.custom.MyCustomGridView;
import com.pps.model.Channel;
import com.pps.model.DetailModel;
import com.pps.utils.ArraysUtils;
import com.pps.utils.DownXML;
import com.pps.utils.FileUtils;
import com.pps.utils.ZipToFile;
import com.pps.xmlparser.DetailXmLSax;

/**
 * 视频详情Fragment显示
 * @author jiangqingqing
 *
 */
public class MyDetailFragment extends Fragment {
	private ImageButton btn_ic_title_menu;
	private TextView detail_name;
	private ImageView detail_img;
	private TextView tv_detail_region;
	private TextView tv_detail_type;
	private Button btn_detail_vm;
	private TextView tv_detail_dirt;
	private TextView tv_detail_actor;
	private Button btn_detail_play;
	private Button btn_detail_down;
	private TextView tv_detail_story;
	private Button btn_detail_arrow_up_commom;
	private Button btn_detail_arrow_down_commom;
	private Button btn_detail_arrow_up_high;
	private Button btn_detail_arrow_down_high;
	private Button btn_detail_arrow_up_advance;
	private Button btn_detail_arrow_down_advance;
	
	private LinearLayout commom_linear_up;
	private LinearLayout high_linear_up;
    private LinearLayout advance_linear_up;
    private LinearLayout commom_linear_down;
	private LinearLayout high_linear_down;
    private LinearLayout advance_linear_down;
	
	private ImageButton btn_details_left;
	private MyCustomGridView gv_detail;
	private Button btn_detail_favour;
	private Button btn_detail_share;
	private Button btn_detail_comment;
	private ImageButton btn_details_right;

	private List<DetailModel> mLists;
	private List<Channel> channels;
	private List<Channel> convert_Channels;
	private List<Channel> commom_Channels;  //普通视频
	private List<Channel> high_Channels;    //高清视频
	private List<Channel> feature_Channels; //花絮视频
	private DetailModel detailModel;
	private MyDetailGridAdapter mAdapter;
	//private SubModel subModel;
	private int sub_id; //用于去请求该节目的详细数据,组合请求的URL
	private ImageLoader imageLoader;
	
	private View mView;
	private Context mContext;
	private static final String TAG="MyDetailFragment";
	
	private Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;
			case 1:
				mLists = (List<DetailModel>) msg.obj;
				if (mLists != null) {
					detailModel = mLists.get(0);
					
				} else {
				}
				detail_name.setText(detailModel.getName());
				//myImageLoader.displayImageView(detailModel.getImg(), detail_img);
				imageLoader.DisplayImage(detailModel.getImg(), getActivity(),detail_img );
				tv_detail_region.setText(detailModel.getRegion());
				tv_detail_type.setText(detailModel.getType());
				btn_detail_vm.setText(String.valueOf(detailModel.getVote()));
				tv_detail_dirt.setText(detailModel.getDirt());
				tv_detail_actor.setText(detailModel.getActor());
                tv_detail_story.setText(detailModel.getInton());
                
                System.out.println("简介:"+detailModel.getInton());
				
                channels = detailModel.getChannels();
				//对视频按照普通，高清，花絮进行分类
				for(int i=0;i<channels.size();i++)
				{
					if("预告花絮".equals(channels.get(i).getType()))
					{
						//预告花絮
						feature_Channels.add(channels.get(i));
						
					}else if ("普通".equals(channels.get(i).getFotm())||"流畅".equals(channels.get(i).getFotm())) {
						//普通视频
						commom_Channels.add(channels.get(i));
						
					}else if ("高清".equals(channels.get(i).getFotm())) {
						//高清视频
						high_Channels.add(channels.get(i));						
					}
				}
				System.out.println("预告花絮集数:"+feature_Channels.size());
				System.out.println("普通视频集数:"+commom_Channels.size());
				System.out.println("高清视频集数:"+high_Channels.size());
				
				//默认刚开始进入的是普通视频列表
				//如果普通视频和高清视频都为空，只有花絮的时候，那就直接显示花絮
				if(feature_Channels.size()!=0&&commom_Channels.size()==0)
				{
					//此刻直接先进入预告花絮栏
					mAdapter = new MyDetailGridAdapter(mContext, feature_Channels);
					gv_detail.setNumColumns(1);
					gv_detail.setAdapter(mAdapter);	
				}else {
					mAdapter = new MyDetailGridAdapter(mContext, commom_Channels);
					gv_detail.setAdapter(mAdapter);	
				}
				
				break;
			}
		}
	};
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(mView==null)
		{
			
			mView=inflater.inflate(R.layout.fragment_detail, container, false);
			initView();
			initVariable();
			Thread thread=new Thread(runnable_id);
			thread.start();
			bindData();
			initListener();
		}
		return mView;
	}
	private void initView() {
		btn_ic_title_menu = (ImageButton) mView
				.findViewById(R.id.btn_ic_title_menu);
		btn_ic_title_menu.setBackgroundResource(0);//去除按钮背景
		detail_name=(TextView)mView.findViewById(R.id.detail_name);
		detail_img = (ImageView) mView.findViewById(R.id.detail_img);
		tv_detail_region = (TextView) mView.findViewById(R.id.tv_detail_region);
		tv_detail_type = (TextView) mView.findViewById(R.id.tv_detail_type);
		btn_detail_vm = (Button) mView.findViewById(R.id.btn_detail_vm);
		tv_detail_dirt = (TextView) mView.findViewById(R.id.tv_detail_dirt);
		tv_detail_actor = (TextView) mView.findViewById(R.id.tv_detail_actor);
		btn_detail_play = (Button) mView.findViewById(R.id.btn_detail_play);
		btn_detail_down = (Button) mView.findViewById(R.id.btn_detail_down);
		tv_detail_story = (TextView) mView.findViewById(R.id.tv_detail_story);
		btn_details_left = (ImageButton) mView.findViewById(R.id.btn_details_left);
		
		btn_detail_arrow_up_commom = (Button) mView
				.findViewById(R.id.btn_detail_arrow_up_commom);
		btn_detail_arrow_down_commom = (Button) mView
				.findViewById(R.id.btn_detail_arrow_down_commom);
		btn_detail_arrow_up_high=(Button)mView.findViewById(R.id.btn_detail_arrow_up_high);
		btn_detail_arrow_down_high=(Button)mView.findViewById(R.id.btn_detail_arrow_down_high);
		
		btn_detail_arrow_up_advance=(Button)mView.findViewById(R.id.btn_detail_arrow_up_advance);
		btn_detail_arrow_down_advance=(Button)mView.findViewById(R.id.btn_detail_arrow_down_advance);

		commom_linear_up=(LinearLayout) mView.findViewById(R.id.commom_linear_up);
		high_linear_up=(LinearLayout)mView.findViewById(R.id.high_linear_up);
        advance_linear_up=(LinearLayout)mView.findViewById(R.id.advance_linear_up);
        commom_linear_down=(LinearLayout) mView.findViewById(R.id.commom_linear_down);
		high_linear_down=(LinearLayout)mView.findViewById(R.id.high_linear_down);
        advance_linear_down=(LinearLayout)mView.findViewById(R.id.advance_linear_down);
        
        btn_details_right = (ImageButton) mView.findViewById(R.id.btn_details_right);
		
		gv_detail = (MyCustomGridView) mView.findViewById(R.id.gv_detail);
		btn_detail_favour = (Button) mView.findViewById(R.id.btn_detail_favour);
		btn_detail_share = (Button) mView.findViewById(R.id.btn_detail_share);
		btn_detail_comment = (Button) mView
				.findViewById(R.id.btn_detail_comment);
		
	}
	private void initVariable() {
		mContext=mView.getContext();
		commom_Channels=new ArrayList<Channel>();
		high_Channels=new ArrayList<Channel>();
		feature_Channels=new ArrayList<Channel>();
		imageLoader=new ImageLoader(mContext);
		btn_details_left.setBackgroundResource(0);
		btn_details_right.setBackgroundResource(0);
		Bundle bundle = getArguments();
		if(bundle!=null)
		{
			sub_id=bundle.getInt("sub_id");
		}
	}
	private void bindData() {		
	}
	private void initListener() {
		btn_ic_title_menu.setOnClickListener(new MyOnClickListener());
		btn_detail_vm.setOnClickListener(new MyOnClickListener());
		btn_detail_play.setOnClickListener(new MyOnClickListener());
		btn_detail_down.setOnClickListener(new MyOnClickListener());
		btn_details_left.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_up_commom.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_down_commom.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_up_high.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_down_high.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_up_advance.setOnClickListener(new MyOnClickListener());
		btn_detail_arrow_down_advance.setOnClickListener(new MyOnClickListener());
		
		commom_linear_up.setOnClickListener(new MyOnClickListener());
		high_linear_up.setOnClickListener(new MyOnClickListener());
		advance_linear_up.setOnClickListener(new MyOnClickListener());
		commom_linear_down.setOnClickListener(new MyOnClickListener());
		high_linear_down.setOnClickListener(new MyOnClickListener());
		advance_linear_down.setOnClickListener(new MyOnClickListener());
		
		btn_details_right.setOnClickListener(new MyOnClickListener());
		btn_detail_favour.setOnClickListener(new MyOnClickListener());
		btn_detail_share.setOnClickListener(new MyOnClickListener());
		btn_detail_comment.setOnClickListener(new MyOnClickListener());
		gv_detail.setOnItemClickListener(new MyOnItemClickListener());
	}	
	/*
	 * 表格布局的Item点击监听器
	 */
	class MyOnItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, final int agr2,
				long arg3) {
			//进行播放视频
			int index= agr2+1;
			Toast.makeText(mContext, "准备播放第"+ index +"集", Toast.LENGTH_SHORT).show();
		}
	}
	/*
	 * 自定义按钮监听器
	 */
	class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			FragmentManager fragmentManager=getFragmentManager();
			FragmentTransaction transaction=fragmentManager.beginTransaction();
			switch (v.getId()) {
			case R.id.btn_ic_title_menu:
				//返回列表页
				MyListFragment listFragment=new MyListFragment();
				transaction.remove(fragmentManager.findFragmentById(R.id.container_details));
				transaction.replace(R.id.container, listFragment);
				transaction.commit();
				break;
			case R.id.btn_detail_vm:
				//进行评分
				break;
			case R.id.btn_detail_play:
				break;
			case R.id.btn_detail_down:
				break;
			case R.id.btn_details_left:
				
				break;
			case R.id.btn_detail_arrow_up_commom:
				//节目按照上升进行布局
				mAdapter = new MyDetailGridAdapter(mContext, commom_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.btn_detail_arrow_down_commom:
				//节目按照下降进行布局
				convert_Channels=ArraysUtils.convertArrays(commom_Channels);
				mAdapter = new MyDetailGridAdapter(mContext, convert_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.btn_detail_arrow_up_high:
				mAdapter = new MyDetailGridAdapter(mContext, high_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.btn_detail_arrow_down_high:
				convert_Channels=ArraysUtils.convertArrays(high_Channels);
				mAdapter = new MyDetailGridAdapter(mContext, convert_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;					
			case R.id.btn_detail_arrow_up_advance:	
				//预告花絮视频上升排列
				mAdapter = new MyDetailGridAdapter(mContext, feature_Channels);
				gv_detail.setNumColumns(1);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.btn_detail_arrow_down_advance:
				//预告花絮视频下降排列
				convert_Channels=ArraysUtils.convertArrays(feature_Channels);
				mAdapter = new MyDetailGridAdapter(mContext, convert_Channels);
				gv_detail.setNumColumns(1);
				gv_detail.setAdapter(mAdapter);
				break;			
			case R.id.commom_linear_up:
				mAdapter = new MyDetailGridAdapter(mContext, commom_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.high_linear_up:
				mAdapter = new MyDetailGridAdapter(mContext, high_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.advance_linear_up:
				mAdapter = new MyDetailGridAdapter(mContext, feature_Channels);
				gv_detail.setNumColumns(1);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.commom_linear_down:
				mAdapter = new MyDetailGridAdapter(mContext, commom_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.high_linear_down:
				mAdapter = new MyDetailGridAdapter(mContext, high_Channels);
				gv_detail.setNumColumns(5);
				gv_detail.setAdapter(mAdapter);
				break;
			case R.id.advance_linear_down:
				mAdapter = new MyDetailGridAdapter(mContext, feature_Channels);
				gv_detail.setNumColumns(1);
				gv_detail.setAdapter(mAdapter);
				break;		
			case R.id.btn_details_right:
				break;
			case R.id.commom_linear:
				
				break;
			case R.id.btn_detail_favour:
				//收藏
				break;
			case R.id.btn_detail_share:
				//分享
				break;
			case R.id.btn_detail_comment:
				//评论
				break;
			}
		}
	}
	
	/**
	 * 根据传来的节目id去后台获取节目的详情
	 */
	Runnable runnable_id = new Runnable() {
		@Override
		public void run() {
			try {
				//1，去网络上面请求数据(根据传来的节目的id)
				String url_str="http://list1.ppstream.com/mobile/newipadc/detail/"+sub_id+".xml.zip";
				DownXML.getFile(url_str);
				String[] strs=url_str.split("/");
	            Log.i(TAG, "请求的URL地址为："+url_str);
				//暂时使用
	            //InputStream inputStream = MyDetailFragment.class.getClassLoader().getResourceAsStream("165562.xml");
	            boolean flag = ZipToFile.unzip("/sdcard", strs[strs.length-1], "/sdcard/"+sub_id+".xml");  
	  	        if(flag) {  
	  	            Log.i(TAG, ">>>>>>>解压成功<<<<<<<<");
	  	            //解压成功，并且删除该压缩包,
	  	            File file=new File("/sdcard/"+sub_id+".xml.zip");
	  	            if(file.exists())
	  	            {
	  	            	file.delete();
	  	            }
	  	        } else {  
	  	        	Log.i(TAG, ">>>>>>>解压失败<<<<<<<<");
	  	        } 
	  	        //测试使用
	  	        InputStream inputStream=DownXML.getXMLFromFile(new File("/sdcard/"+sub_id+".xml/"+sub_id+".xml"));	  	        
	  	        SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser parser = spf.newSAXParser();
				//DetailXMLContentHandler handler = new DetailXMLContentHandler();
				DetailXmLSax handler=new DetailXmLSax();
				parser.parse(inputStream, handler);
				inputStream.close();
				mLists = handler.getDetailLists();
				mHandler.obtainMessage(1, mLists).sendToTarget();
				//删除解压后的XML文件夹
				FileUtils.deleteAll(new File("/sdcard/"+sub_id+".xml"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
}
